# coding:utf8
import requests
import re
# 以下分别是2.7和3版本的同一功能的包   兼容代码
try:
    import cookielib

except:
     import http.cookiejar as cookielib


session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename="cookies.txt")
try:
    session.cookies.load(ignore_discard=True)
except:
    print ("cookies未能加载成功")

agent = "Mozilla/5.0 (Windows NT 6.1; Win64; " \
        "x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

header = {
    "HOST":"www.zhihu.com",
    "Referer":"https://www.zhihu.com/",
    "User-Agent":agent,
}


def is_login():
    inbox_url = "https://www.zhihu.com/inbox"
    response = session.get(inbox_url, headers=header, allow_redirects=False)
    if response.status_code != 200:
        return False
    else:
        return True


def get_xsrf():
    # 获取 _xsrf 的值
    response = session.get("https://www.zhihu.com", headers=header)


    # print text
    # 匹配换行的问题
    match_obj = re.match('.*name="_xsrf" value="(.*?)"', response.text, re.DOTALL)
    if match_obj:
        print (match_obj.group(1))
        return match_obj.group(1)
    else:
        return "===================match failed!========================"


def getCaptcha_type():
    # 获取 _xsrf 的值
    response = session.get("https://www.zhihu.com", headers=header)


    # print text
    # 匹配换行的问题
    match_obj = re.match('.*name="captcha_type" value="(.*?)"', response.text, re.DOTALL)
    if match_obj:
        print (match_obj.group(1))
        return match_obj.group(1)
    else:
        return "===================match failed!========================"


def get_index():
    '''
    文件的读写时，utf8和unicode编码的转换！
    :return:
    '''
    response = session.get("https://www.zhihu.com", headers=header)
    with open("index_page.html", 'wb') as f:
        f.write(response.text.encode('utf8'))
    print "ok"


def get_captcha():
    import time
    t = str(int(time.time()*1000))
    captcha_url = "https://www.zhihu/captcha.gif?r={0}&type=login".format(t)
    t = session.get(captcha_url, headers=header)
    with open("captcha.jpg", "wb") as f:
        f.write(t.content)
        f.close()


def zhihu_login(account, password):
    # 知乎登录
    if re.match("^1\d{10}", account):
        print ("--------------------手机号码登录-----------------------")
        post_url = "https://www.zhihu.com/login/phone_num"
        post_data = {
            "_xsrf": get_xsrf(),
            "captcha_type": getCaptcha_type(),
            "phone_num": account,
            "password": password,
        }

    else:
        if "@" in account:
            # 判断用户是否为邮箱
            print ("--------------------邮箱方式登录-----------------------")
            post_url = "https://www.zhihu.com/login/phone_num"
            post_data = {
                "_xsrf": get_xsrf(),
                "captcha_type": getCaptcha_type(),
                "phone_num": account,
                "password": password,

            }

    response_text = session.post(post_url, data=post_data, headers=header)
    session.cookies.save()

# 验证会话无效
zhihu_login('18755132178', '448537056zhihu')
# get_index()
# is_login()
# get_captcha()